//	发送一个"高电位有效"复位脉冲给idelayctrl

#include "MephistoCAM.h"

int main( int argc, char *argv[] ){

//	检查idelayctrl的rdy信号
	int fd_gpio = open("/dev/mem", O_RDWR | O_SYNC);
	uint *ptr1 = mmap(NULL, 10, PROT_READ | PROT_WRITE, MAP_SHARED, fd_gpio, ADDR_GPIO_OUT);
	uint *ptr2 = mmap(NULL, 10, PROT_READ | PROT_WRITE, MAP_SHARED, fd_gpio, ADDR_GPIO_IN);

	uint *gpio_reg 		= ptr1;		// 0x41200000
	// uint *gpio2_reg		= ptr1+2;	// 0x41200008
	uint *gpio_in_reg	= ptr2;		// 0x41210000

	printf("/**********************************************/\n");

	int rdy  = getbit(*gpio_in_reg, BIT_IDELAYCTRL_RDY_X);

	if( rdy == 1 ){
		printf("==> idelayctrl is ready!\n");
	} else {
		printf("==> idelayctrl is NOT ready!\n");
	}


	//	send a reset pulse to IDELAYCTRL
	printf("--> sending an active-high reset pulse to IDELAYCTRL\n");
	clrbit(*gpio_reg, BIT_IDELAYCTRL_RDY_X);
	clrbit(*gpio_reg, BIT_IDELAYCTRL_RDY_Y);
	usleep(10);
	setbit(*gpio_reg, BIT_IDELAYCTRL_RDY_X);
	setbit(*gpio_reg, BIT_IDELAYCTRL_RDY_Y);
	usleep(10);
	clrbit(*gpio_reg, BIT_IDELAYCTRL_RDY_X);
	clrbit(*gpio_reg, BIT_IDELAYCTRL_RDY_Y);
	printf("--> sending pulse is over!\n");

	int cnt = 0;
	rdy = 0;

	usleep(10);

	printf("--> re-check IDELAYCTRL RDY status ...\n");
	while( rdy != 1 ){

		rdy = getbit(*gpio_in_reg, BIT_IDELAYCTRL_RDY_X);

		if( rdy == 1 ){
			printf("##> idelayctrl is now ready!!!!\n");
			break;
		}

		usleep(10);
		
		cnt++;
		if( cnt >= 10 ){
			printf("##> idelayctrl is still NOT ready!!!!\n");
			break;
		}
	}

	printf("/**********************************************/\n");

	munmap(ptr1,10);
	munmap(ptr2,10);

	return 0;
}
